﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using STF.Blog.Common;
using STF.Blog.Dtos;
using STF.Blog.IService;
using STF.Blog.WebApp.Models.Article;
using STF.Blog.WebApp.Models.Author;
using STF.Blog.WebApp.Models.Creation;
using STF.Blog.WebApp.Models.Index;
using STF.Blog.WebApp.Models.Layout;
using STF.Blog.WebApp.Models.UserInfo;
using STF.Blog.WebApp.Tools;

namespace STF.Blog.WebApp.Controllers
{
    public class HomeController : Controller
    {
        private IUsersService _iusersSvc;
        private IUsersInfoService _iusInfoSvc;
        private ICategoryService _categorySvc;
        private IWebHostEnvironment _webHostEnvironment;
        private IBlogService _blogService;
        private ICoverService _coverService;
        private IFriendLinkService _friendLinkService;
        private ICopyrightService _copyrightService;
        private IWebHostEnvironment _webHe;
        private ILevelService _levelService;
        private IReleaseFormService _releaseFormService;
        private IArticleCateGoryService _articleCateGoryService;
        private IClassifyColumnService _classifyColumnService;
        private ICommentService _commentService;
        private IReplyService _replyService;
        private IArticleCategoryOwnershipService _articleCategoryOwn;
        private IBlogCateGoryService _blogCateGoryService;
        public HomeController(IUsersService iusersSvc, IUsersInfoService iusInfoSvc,
                              IWebHostEnvironment webHostEnvironment, ICategoryService categorySvc,
                              IBlogService blogService, ICoverService coverService,
                              IFriendLinkService friendLinkService, ICopyrightService copyrightService,
                              IWebHostEnvironment webHe,ILevelService levelService,IReleaseFormService releaseFormService,
                              IArticleCateGoryService articleCateGoryService, IClassifyColumnService classifyColumnService,
                              ICommentService commentService,IReplyService replyService, IArticleCategoryOwnershipService articleCategoryOwn,
                              IBlogCateGoryService blogCateGoryService)
        {
            _iusersSvc = iusersSvc;
            _iusInfoSvc = iusInfoSvc;
            _categorySvc = categorySvc;
            _webHostEnvironment = webHostEnvironment;
            _blogService = blogService;
            _coverService = coverService;
            _friendLinkService = friendLinkService;
            _copyrightService = copyrightService;
            _webHe = webHe;
            _levelService = levelService;
            _releaseFormService = releaseFormService;
            _articleCateGoryService = articleCateGoryService;
            _classifyColumnService = classifyColumnService;
            _commentService = commentService;
            _replyService = replyService;
            _articleCategoryOwn = articleCategoryOwn;
            _blogCateGoryService = blogCateGoryService;
        }

        [HttpGet]
        public IActionResult Index()
        {
            ViewBag.Title = "GBlog -- 全网最水的博客平台";
            return View();
        }

        [HttpGet]
        public IActionResult Login() 
        {
            ViewBag.Title = "登录";
            return View();
        }

        [HttpGet]
        public IActionResult UserInfo() 
        {
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> AuthorInfo(int id) 
        {
            var blogInfo = await _blogService.GetByIdAsync(id);
            var BlogAuthorInfo = await _iusersSvc.GetByIdAsync(blogInfo.Uid);
            var BlogAuthorPhoto = await _iusInfoSvc.GetByIdAsync(BlogAuthorInfo.Id);

            ViewBag.AuthorId = BlogAuthorInfo.Id;
            ViewBag.AuthorName = BlogAuthorInfo.NickName;
            ViewBag.AuthorPhoto = BlogAuthorPhoto.Photo;
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> GetColumn(int id) 
        {
            var data = await _classifyColumnService.GetByIdListAsync(id);
            var list = new List<AuthorColumnListViewModel>();

            foreach (var i in data)
            {
                list.Add(new AuthorColumnListViewModel 
                {
                    Id = i.Id,
                    ColumnName = i.Title
                });
            }
            return Json(list);
        }

        [HttpGet]
        public async Task<IActionResult> GetAuthorArticle(int id) 
        {
            var data = await _blogService.GetByUidListAsync(id);
            var list = new List<AuthorBlogListViewModel>();

            foreach (var i in data)
            {
                var removeTag = DeleteHtmlTag.DeleteTag(i.Content);
                list.Add(new AuthorBlogListViewModel 
                {
                    Id = i.Id,
                    Title = i.Title,
                    Content = removeTag.Length > 86 ? removeTag.Substring(0,86) : removeTag,
                    Like = i.Like,
                    PublishTime = i.PublishTime.ToString("yyyy年MM月dd日")
                });
            }

            return Json(list);
        }

        [HttpGet]
        public async Task<IActionResult> Article(int id) 
        {
            var data = await _blogService.GetByIdAsync(id);
            var user = await _iusersSvc.GetByIdAsync(data.Uid);
            var userInfo = await _iusInfoSvc.GetByIdAsync(user.Id);
            var comment = await _commentService.GetByBidListAsync(data.Id);
            //var cId = await _commentService.GetByIdAsync(data.Id);
            var reply = await _replyService.GetByReplyInfoListAsync(comment);


            if (data == null || string.IsNullOrEmpty(data.Title))
                return Redirect("../../Home/Index");

            List<CommentViewModel> commentList = new List<CommentViewModel>();
            Dictionary<int,List<ReplyViewModel>> replyList =new Dictionary<int, List<ReplyViewModel>>();

            foreach (var cmt in comment)
            {
                commentList.Add(new CommentViewModel
                {
                    Id = cmt.Id,
                    Content = cmt.Content,
                    LikeSum = cmt.LikeSum,
                    UserName = await GetCommentUserName(cmt.Uid),
                    UserPhoto = await GetCommentUserPhoto(cmt.Uid),
                    CreateTime = cmt.CreateTime.ToString("yyyy年MM月dd日 HH:mm:ss")
                });
            }
            foreach (var a in reply) 
            {
                var list = new List<ReplyViewModel>();
                foreach (var li in a.Value) 
                {
                    list.Add(new ReplyViewModel
                    {
                        Id = li.Id,
                        CommentId = li.Pid,
                        Content = li.Content,
                        LikeSum = li.LikeSum,
                        CreateTime = li.CreateTime.ToString("yyyy年MM月dd日 HH:mm:ss"),
                        ParentUser = await GetReplyParentNmae(li.ParentId),
                        UserPhoto = await GetCommentUserPhoto(li.Uid),
                        UserName = await GetCommentUserName(li.Uid),
                    });
                }
                replyList.Add(a.Key,list);
            }
            ////for (int i = 0; i < reply.Count(); i++)
            ////{
            ////    var replyUserName = await _iusersSvc.GetByIdAsync(reply[i].Uid);

            ////    replyList.Add(new ReplyViewModel
            ////    {
            ////        Id = reply[i].Id,
            ////        CommentId = reply[i].Pid,
            ////        Content = reply[i].Content,
            ////        LikeSum = reply[i].LikeSum,
            ////        UserName = await GetCommentUserName(reply[i].Uid),
            ////        UserPhoto = await GetCommentUserPhoto(reply[i].Uid),
            ////        ParentUser = await GetCommentUserName(reply[i].ParentId),
            ////        CreateTime = reply[i].CreateTime.ToString("yyyy年MM月dd日 HH:mm:ss")
            ////    });
            ////}
            
            

            ViewBag.CommentList = commentList;
            ViewBag.replyList = replyList;
            #region 笨蛋式存值
            //var article = new ArticleViewModel();
            //article.Id = id;
            //article.Title = data.Title;
            //article.Context = data.Content;
            //article.PublishTime = data.PublishTime.ToString("yyyy年MM月dd日");
            //article.Like = data.Like;
            //article.Trample = data.Trample;
            //article.UserTitle = user.NickName;
            //article.UserPhoto = userInfo.Photo;
            #endregion

            return View(new ArticleViewModel 
            {
                Id = id,
                Title = data.Title,
                Context = data.Content,
                PublishTime = data.PublishTime.ToString("yyyy年MM月dd日"),
                Like = data.Like,
                Trample = data.Trample,
                UserTitle = user.NickName,
                UserPhoto = userInfo.Photo
            });
        }

        [HttpGet]
        public async Task<IActionResult> AddComment(string content,string articleId) 
        {
            var userInfo = HttpContext.Session.GetString("user");

            if(ModelState.IsValid) 
            {
                var res = await _commentService.AddCommentAsync(int.Parse(articleId),content,0,int.Parse(userInfo));
                if (res > 0)
                    return Json("true");
            }
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> AddCommentRep(string content,string id) 
        {
            var userInfo = HttpContext.Session.GetString("user");

            if (ModelState.IsValid) 
            {
                var res = await _replyService.AddReplyAsync(int.Parse(id),content,0,0,int.Parse(userInfo));
                if (res > 0)
                    return Json("true");
            }
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> AddReplyParent(string content,string id) 
        {
            var userInfo = HttpContext.Session.GetString ("user");

            var a = await _replyService.GetByIdAsync(int.Parse(id));


            if (ModelState.IsValid)
            {
                var res = await _replyService.AddReplyAsync(a.Pid,content,int.Parse(id),0,int.Parse(userInfo));
                if (res > 0)
                    return Json("true");
            }

            return View();
        }

        [HttpPost]
        public async Task<IActionResult> ArticleLike(int LikeSumId) 
        {
            if (ModelState.IsValid) 
            {
                var like = await _blogService.GetByIdAsync(LikeSumId);
                var res = await _blogService.UpdateBlogAsync(like.Id, like.Title, like.Content, like.PublishTime, 2, like.Like +1, like.Trample,like.TypeId, like.FbxsId, like.LevelId, like.Uid, like.CoverId);
                if (res > 0)
                    return Json(await _blogService.GetByIdAsync(LikeSumId));
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> ArticleTrample(int TrampleId) 
        {
            if (ModelState.IsValid) 
            {
                var trample = await _blogService.GetByIdAsync(TrampleId);
                var sum = 0;
                sum = trample.Like <= 0 ? sum = 0 : trample.Like - 1;
                var res = await _blogService.UpdateBlogAsync(trample.Id, trample.Title, trample.Content, trample.PublishTime, 2, sum, trample.Trample, trample.TypeId, trample.FbxsId, trample.LevelId, trample.Uid, trample.CoverId);
                if (res > 0)
                    return Json(await _blogService.GetByIdAsync(TrampleId));
            }
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> CommentLike(int CommentLikeId) 
        {
            if (ModelState.IsValid) 
            {
                var like = await _commentService.GetByIdAsync(CommentLikeId);
                var res = await _commentService.UpdateCommentAsync(like.Id,like.Bid,like.Content,like.LikeSum+1,like.Uid);
                if (res > 0)
                    return Json(await _commentService.GetByIdAsync(CommentLikeId));
            }
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> CommentTrample(int CommentTrampleId) 
        {
            if (ModelState.IsValid) 
            {
                var trample = await _commentService.GetByIdAsync(CommentTrampleId);
                var sum = 0;
                sum = trample.LikeSum <= 0 ? sum = 0 : trample.LikeSum - 1;

                var res = await _commentService.UpdateCommentAsync(trample.Id, trample.Bid, trample.Content, sum, trample.Uid);
                if (res > 0)
                    return Json(await _commentService.GetByIdAsync(CommentTrampleId));
            }
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> ReplyLike(int replyLikeId) 
        {

            if (ModelState.IsValid) 
            {
                var like = await _replyService.GetByIdAsync(replyLikeId);
                var data = await _replyService.UpdateReplyAsync(like.Id,like.Pid,like.Content,like.ParentId,like.LikeSum+1,like.Uid);
                if (data > 0)
                    return Json(await _replyService.GetByIdAsync(replyLikeId));
            }
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> ReplyTrample(int replyTrampleId) 
        {
            if (ModelState.IsValid) 
            {
                var trample = await _replyService.GetByIdAsync(replyTrampleId);
                var sum = 0;
                sum = trample.LikeSum <= 0 ? sum = 0 : trample.LikeSum - 1;

                var res = await _replyService.UpdateReplyAsync(trample.Id, trample.Pid, trample.Content, trample.ParentId, sum, trample.Uid);
                if (res > 0)
                    return Json(await _replyService.GetByIdAsync(replyTrampleId));
            }
            return View();
        }

        [HttpGet]
        public IActionResult CateGory(int id = 1, int? typeId = 0) 
        {
            ViewBag.Id = id;
            ViewBag.Pid = typeId != null ? typeId : 0;
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> GetCtType(int cgId) 
        {
            var data = await _categorySvc.GetByParentIdAsync(cgId);
            return Json(data);
        }

        [HttpGet]
        public async Task<IActionResult> Creation() 
        {
            var userId = HttpContext.Session.GetString("user");
            var ArticleType = await _categorySvc.GetByParentIdAsync(0);
            var LevelTyle = await _levelService.GetAllLevelAsync();
            var ReleForm = await _releaseFormService.GetAllRfAsync();
            var Article = await _articleCateGoryService.GetAllArticleCateGoryAsync();
            var classColumn = await _classifyColumnService.GetByIdListAsync(int.Parse(userId));
            ViewBag.Article = ArticleType;
            ViewBag.Level = LevelTyle;
            ViewBag.ReleaseForm = ReleForm;
            ViewBag.ArticleList = Article;
            ViewBag.ArticleTag = new SelectList(ArticleType,"Id","Title");
            ViewBag.ClassColumn = new SelectList(classColumn,"Title","Title");
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Creation(CreationListViewModel model) 
        {
            if (ModelState.IsValid) 
            {
                var strTag = "";
                for (int i = 0; i < model.ArticleTagList.Length; i++)
                {
                    if (i < model.ArticleTagList.Length - 1)
                        strTag += model.ArticleTagList[i] += ",";
                    else
                        strTag += model.ArticleTagList[i];
                }
                var userId = HttpContext.Session.GetString("user");
                var img = await UploadFiles(model.Cover,@"\Web\Cover");
                var cover = await _coverService.AddCoverAsync("", img, "", "");
                var coverId = await _coverService.GetBlogCoverId(img);
                
                var blog = await _blogService.AddBlogAsync(model.Title,model.Context,DateTime.Now,1,0,0,model.ArticleCategoryTitle,model.ReleaseFormTitle,model.LevelTitle,int.Parse(userId),coverId.Id);
                var bid = await _blogService.GetByBidAsync(int.Parse(userId));
                var classColumn = await _classifyColumnService.GetByCid(model.ClassColumn);
                var articleTag = await _blogCateGoryService.AddBlogCateGoryAsync(bid,strTag);
                var classColumnOwp = await _articleCategoryOwn.AddAcoAsync(bid, classColumn);
                if (cover > 0 && blog > 0 && classColumnOwp > 0 && articleTag > 0)
                    return Redirect("../../Home/Index");
            }
            var LevelTyle = await _levelService.GetAllLevelAsync();
            var ReleForm = await _releaseFormService.GetAllRfAsync();
            var Article = await _articleCateGoryService.GetAllArticleCateGoryAsync();
            ViewBag.Level = LevelTyle;
            ViewBag.ReleaseForm = ReleForm;
            ViewBag.ArticleList = Article;
            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> GetTagParentList(int parentId) 
        {
            var list = await _categorySvc.GetByParentIdAsync(parentId);
            return Json(list);
        }

       [HttpPost]
       public async Task<IActionResult> Login(string account, string pwd) 
       {
           if (ModelState.IsValid) 
           {
               var data = await _iusersSvc.LoginAsync(account, pwd);
               if (data <= 0) 
               {
                   var notData = await _iusersSvc.AddUsersAsync(account,pwd,"default.png",1);
                   var userid = await _iusersSvc.GetUserByNameAsync(account);
                   await _iusInfoSvc.AddUsersInfoAsync("",DateTime.Now,2,"","","","default.png",0,userid);
                    if (notData > 0) 
                    {
                        HttpContext.Session.SetString("user",data.ToString());
                        return Redirect("~/Home/Index");
                    }
                    return View();
               }
                HttpContext.Session.SetString("user", data.ToString());
                return Redirect("~/Home/Index");
           }
            return View();
       }

        [HttpGet]
        public async Task<IActionResult> GetUserPhoto() 
        {
            var data = HttpContext.Session.GetString("user");
            if (data == null)
                return Json(null);
            var User = await _iusersSvc.GetByIdAsync(int.Parse(data));
            var UserInfo = await _iusInfoSvc.GetUserIdAsync(User.Id);
            if (UserInfo == null)
                return Json(null);
            return Json(new LayouyViewModel 
            {
                UserImage = UserInfo.Photo,
                UserName = UserInfo.RealName
            });
        }

        [HttpGet]
        public async Task<IActionResult> GetCateGory() 
        {
            var data = await _categorySvc.GetByParentIdAsync(0);
            var CgList = data.Select(cg => new IndexCateGoryListViewModel 
            {
                Id = cg.Id,
                Title = cg.Title
            });
            return CgList == null ? null : Json(CgList);
        }

        [HttpGet]
        public async Task<IActionResult> GetUserInfo() 
        {
            var userSession = HttpContext.Session.GetString("user");
            if (userSession == null)
                return Json(null);
            var data = await _iusersSvc.GetByIdAsync(int.Parse(userSession));
            var InfoData = await _iusInfoSvc.GetUserIdAsync(data.Id);
            return Json(new UserInfoListViewModel 
            {
                Id = data.Id,
                NickName = data.NickName,
                RealName = InfoData.RealName,
                Birthday = InfoData.Birthday,
                Gender = InfoData.Gender,
                WeChat = InfoData.WeChat,
                Tel = InfoData.Tel,
                Address = InfoData.Address,
                Photo = InfoData.Photo
            });
        }

        [HttpPost]
        public async Task<IActionResult> EditUserInfo(string nickName, string realName, DateTime birthday, int gender, string weChat, string tel, string address, IFormFile photo) 
        {
            var usId = HttpContext.Session.GetString("user");
            var user = await _iusersSvc.GetByIdAsync(int.Parse(usId));
            var userInfo = await _iusInfoSvc.GetByIdAsync(user.Id);
            var img = await UploadFiles(photo,@"\Web\UsersImage");

            if (string.IsNullOrEmpty(img)) 
            {
                img = userInfo.Photo;
            }

            int userRes = await _iusersSvc.UpdateUsersAsync(user.Id, user.Email, user.Pwd, nickName, user.StateCode);
            int userInfoRes = await _iusInfoSvc.UpdateUsersInfoAsync(userInfo.Id,realName, birthday, gender,weChat,tel,address,img,userInfo.Amount,user.Id);

            if (userRes > 0 && userInfoRes > 0) 
            {
                return Redirect("~/Home/UserInfo");
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> UpdateUserAP(string weChat,string tel) 
        {
            var usId = HttpContext.Session.GetString("user");
            var user = await _iusersSvc.GetByIdAsync(int.Parse(usId));
            var UserInfo = await _iusInfoSvc.GetByIdAsync(user.Id);

            int res = await _iusInfoSvc.UpdateUsersInfoAsync(UserInfo.Id, UserInfo.RealName, UserInfo.Birthday,(int)UserInfo.Gender, weChat,tel, UserInfo.Address, UserInfo.Photo, UserInfo.Amount, UserInfo.Uid);
            if (res > 0)
                return Redirect("~/Home/UserInfo");

            return View();
        }

        private async Task<string> UploadFiles(IFormFile images, string url)
        {
            string imgName = "";
            if (images != null && images.FileName != null)
            {
                imgName = DateTime.Now.ToString("yyyyMMddHHmmss") +
                           images.FileName.Substring(images.FileName.LastIndexOf("."));

                string directPath = _webHostEnvironment.WebRootPath + url; //设定上传到
                                                           //目录名称
                string path = Path.Combine(directPath, imgName); //把我们的内容设定成绝对路径
                images.CopyTo(new FileStream(path, FileMode.Create));
            }
            return imgName;
        }

        [HttpGet]
        public async Task<IActionResult> GetUserArticle() 
        {
            var user = HttpContext.Session.GetString("user");
            var UserArticle = await _blogService.GetByIdListAsync(int.Parse(user));
            var ArticleList = new List<UserArticleListViewModel>();

            foreach (var blog in UserArticle)
            {
                var removeTag = DeleteHtmlTag.DeleteTag(blog.Content);

                ArticleList.Add(new UserArticleListViewModel
                {
                    Id = blog.Id,
                    Title = blog.Title,
                    Context = removeTag.Length > 86 ? removeTag.Substring(0,85) + "..." : removeTag,
                    Photo = await GetBlogCover(blog.CoverId)
                });
            }
            return Json(ArticleList);
        }

        [HttpGet]
        public async Task<IActionResult> GetCateGoryArticle(int id, int parentId) 
        {
            var data = await _blogService.GetAllBlogAsync();

            var CateGoryArticleList = parentId == 0 ? await _blogCateGoryService.GetParentIdOne(id)
                                                    : await _blogCateGoryService.GetParentIdTwo(parentId);

            var ArticleList = new List<IndexArticleListViewModel>();

            for (int i = 0; i < CateGoryArticleList.Count; i++)
            {
                for (int j = 0; j < data.Count; j++)
                {
                    if (data[j].Id == CateGoryArticleList[i].Bid && data[j].StateCode == (StateCode)2)
                    {
                        var removeTag = DeleteHtmlTag.DeleteTag(data[j].Content);
                        ArticleList.Add(new IndexArticleListViewModel
                        {
                            Id = data[j].Id,
                            Title = data[j].Title,
                            Context = removeTag.Length > 120 ? removeTag.Substring(0, 120) : removeTag,
                            Like = data[j].Like,
                            Trample = data[j].Trample,
                            Photo = await GetBlogCover(data[j].CoverId),
                            Author = await GetBlogAuthor(data[j].Uid)
                        });
                    }
                }
            }
            
            return Json(ArticleList);
        }

        [HttpGet]
        public async Task<IActionResult> GetArticleColumn(int aId) 
        {
            var column = await _articleCategoryOwn.GetByBidAsync(aId);

            var columnTitle = await GetColumnTitle(int.Parse(column.Fid));

            return Json(columnTitle);
        }

        [HttpGet]
        public async Task<IActionResult> GetArticle() 
        {
            var data = await _blogService.GetAllBlogAsync();

            //var CateGoryArticleList = parentId == 0 ? await _blogCateGoryService.GetParentIdOne(id) 
            //                                        : await _blogCateGoryService.GetParentIdTwo(parentId);

            var ArticleList = new List<IndexArticleListViewModel>();

            //for (int i = 0; i < CateGoryArticleList.Count; i++)
            //{
            //    if (data[i].Id == CateGoryArticleList[i].Bid && data[i].StateCode == (StateCode)2) 
            //    {
            //        var removeTag = DeleteHtmlTag.DeleteTag(data[i].Content);
            //        ArticleList.Add(new IndexArticleListViewModel
            //        {
            //            Id = data[i].Id,
            //            Title = data[i].Title,
            //            Context = removeTag,
            //            Like = data[i].Like,
            //            Trample = data[i].Trample,
            //            Photo = await GetBlogCover(data[i].CoverId),
            //            Author = await GetBlogAuthor(data[i].Uid)
            //        });
            //    }      
            //}

            foreach (var blog in data)
            {
                var removeTag = DeleteHtmlTag.DeleteTag(blog.Content);
                ArticleList.Add(new IndexArticleListViewModel
                {
                    Id = blog.Id,
                    Title = blog.Title,
                    Context = removeTag.Length > 86 ? removeTag.Substring(0, 86) : removeTag,
                    Like = blog.Like,
                    Trample = blog.Trample,
                    Photo = await GetBlogCover(blog.CoverId),
                    Author = await GetBlogAuthor(blog.Uid)
                });
            }
            return Json(ArticleList);
        }

        [HttpGet]
        public async Task<IActionResult> GetArticleDate() 
        {
            var data = await _blogService.GetByDateAsync();
            var DataList = new List<IndexArticleListViewModel>();
            
            foreach (var blog in data)
            {
                var removeTag = DeleteHtmlTag.DeleteTag(blog.Content);
                DataList.Add(new IndexArticleListViewModel 
                {
                    Id = blog.Id,
                    Title = blog.Title.Length > 25 ? removeTag.Substring(0, 26) : blog.Title,
                    Context = removeTag.Length > 25 ? removeTag.Substring(0, 21) : removeTag,
                    Like = blog.Like,
                    Trample = blog.Trample,
                    Photo = await GetBlogCover(blog.CoverId),
                    Author = await GetBlogAuthor(blog.Uid)
                });
            }
            return Json(DataList);
        }

        [HttpGet]
        public async Task<IActionResult> GetArticleLike() 
        {
            var data = await _blogService.GetByLikeAsync();
            var LikeList = new List<IndexArticleListViewModel>();
            foreach (var blog in data)
            {
                var removeTag = DeleteHtmlTag.DeleteTag(blog.Content);
                LikeList.Add(new IndexArticleListViewModel 
                {
                    Id = blog.Id,
                    Title = blog.Title.Length > 25 ? removeTag.Substring(0, 26) : blog.Title,
                    Context = removeTag.Length > 25 ? removeTag.Substring(0, 21) : removeTag,
                    Like = blog.Like,
                    Photo = await GetBlogCover(blog.CoverId),
                    Trample = blog.Trample,
                    Author = await GetBlogAuthor(blog.Uid)
                });
            }

            return Json(LikeList);
        }

        [HttpGet]
        public async Task<IActionResult> AddClassColumn(string title) 
        {
            if (ModelState.IsValid) 
            {
                var userId = HttpContext.Session.GetString("user");
                var res = await _classifyColumnService.AddClassifyColumnAsync(title,int.Parse(userId));
                if (res > 0)
                    return Json(await _classifyColumnService.GetByIdListAsync(int.Parse(userId)));
            }
            return View();
        }

        private async Task<string> GetColumnTitle(int fid) 
        {
            var data = await _classifyColumnService.GetByIdAsync(fid);
            return data == null ? "" : data.Title;
        }

        private async Task<string> GetBlogAuthor(int id) 
        {
            var data = await _iusersSvc.GetByIdAsync(id);
            return data == null ? "" : data.NickName;
        }

        private async Task<string> GetBlogCover(int id) 
        {
            var data = await _coverService.GetByIdAsync(id);
            return data == null ? "" : data.Image1;
        }

        private async Task<string> GetCommentUserName(int uid) 
        {
            var data = await _iusersSvc.GetByIdAsync(uid);
            return data == null ? "" : data.NickName;
        }

        private async Task<string> GetReplyParentNmae(int parentId) 
        {
            var data = await _replyService.GetByIdAsync(parentId);
            var ParentUser = await _iusersSvc.GetByIdAsync(data.Uid);
            return ParentUser == null ? "" : ParentUser.NickName;
        }

        private async Task<string> GetCommentUserPhoto(int uid) 
        {
            var data = await _iusInfoSvc.GetByIdAsync(uid);
            return data == null ? "" : data.Photo;
        }

        /// <summary>
        /// 这个是我们友情链接的方法
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GerFLink() 
        {
            var data = await _friendLinkService.GetAllUsersAsync();
            var FLink = data.Select(fk => new IndexFLinkListVIewModel 
            {
                Id = fk.Id,
                Title = fk.Title
            }).ToList();
            return Json(FLink);
        }

        /// <summary>
        /// 这个是我们富文本编辑器展示图片的方法
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadImageAjax() 
        {

            //获取编辑器传回来的图片信息
            var fileItem = HttpContext.Request.Form.Files[0];
            var fileName = "";

            //判断它是否为空值
            if (fileItem == null || string.IsNullOrEmpty(fileItem.FileName)) 
                return Json("");

            //将我们传递过来的图片重新命名
            fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileItem.FileName.Substring(fileItem.FileName.LastIndexOf("."));

            //创建一个新的路径
            var PathUrl = _webHe.WebRootPath + @"\summernoteArticleImage\Article";

            //将我们的图片信息传到我们设定的路径里
            var path = Path.Combine(PathUrl, fileName);

            fileItem.CopyTo(new FileStream(path, FileMode.Create));

            return Json(@"\summernoteArticleImage\Article\" + fileName);
        }

    }
}
